import { reactive, onMounted, ref } from 'vue'
/**
 *  封装表格查询的通用方法
 *
 * @param {*} promise 获取表格数据的api
 * @returns
 */
export default function useFetchTable(promise) {
  // 查询参数
  let queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  })

  // 表格数据
  let dataSource = ref([])
  // 总页数
  let total = ref(0)
  // 表格加载
  let tableLoading = ref(false)
  // 获取数据
  const fetchData = () => {
    tableLoading.value = true
    promise(queryParams.value)
      .then((res) => {
        dataSource.value = res.rows
        total.value = res.total
      })
      .finally(() => {
        tableLoading.value = false
      })
  }
  // 表格Size变化时
  const pageSizeChange = (val) => {
    queryParams.value.pageSize = val
    fetchData()
  }
  // 表格页数变化时
  const currentPageChange = (val) => {
    queryParams.value.pageNum = val
    fetchData()
  }
  // 检索
  const search = () => {
    queryParams.value.pageNum = 1
    fetchData()
  }
  // 重置检索
  const reset = () => {
    let value = queryParams.value
    for (let key in value) {
      if (key === 'pageNum') {
        queryParams.value[key] = 1
      } else if (key === 'pageSize') {
        queryParams.value[key] = value[key]
      } else {
        queryParams.value[key] = null
      }
    }
    fetchData()
  }
  // 页面加载时
  onMounted(() => {
    fetchData()
  })
  return {
    queryParams,
    total,
    dataSource,
    tableLoading,
    fetchData,
    pageSizeChange,
    currentPageChange,
    search,
    reset,
  }
}
